﻿from __future__ import print_function

import sys
from wbox.gx import *
from wbox.gx.comment import GxCommentFile

def extractComment(cf, devList):
    L = []
    for dev in devList:
        # 4 종류의 디바이스(M, L, D, R)를 한꺼번에 처리한다. 
        wildcard = False
        if dev.find("*") != -1:
            dev = dev.replace("*", "")
            wildcard = True

        # 처리할 디바이스의 갯수를 얻는다. 
        count = 1
        colon = dev.find(":")
        if colon != -1:
            count = int(dev[colon + 1:], 0)
            dev = dev[:colon]
            
        if wildcard:
            _dev = map(lambda d: d + dev, ["M", "L", "D", "R"])
        else:
            _dev = [dev]
        
        for dev in _dev:
            code = list(deviceName2Code(dev))
            for i in range(count):
                name = deviceCode2Name(*code)
                try:
                    comment = cf.getComment(name)[1]
                    comment = comment.encode("latin-1")
                    comment = comment.decode("euc-kr")
                except KeyError:
                    comment = ""
                L.append("{0}\t{1}".format(name, comment))
                code[1] += 1
            
    return "\n".join(L)
    
    
def fill_comment(comment):
    try:
        result = []
        for comment in comment.split("."):
            comment = comment + " "*7
            length = len(comment)
            result.append(comment[:length - length % 8])
        return "".join(result)
    except:
        print(repr(comment), file=sys.stderr)
        raise

def appendComment(path, text, delimiter='\t'):
    try:
        cf = GxCommentFile()
        cf.load(path)
        for line in text.splitlines():
            info = line.strip().split(delimiter, 1)
            if len(info) < 2:
                device = info[0]
                comment = ""
            else:
                device, comment = info
            comment = comment.encode("euc-kr")
            #comment = comment.decode("latin-1")
            try:
                cf.setComment(device, fill_comment(comment))
            except:
                print(device, comment, file==sys.stderr)
                raise
    except Exception as ex:
        import traceback 
        traceback.print_exc()
    else:
        cf.save()
        
def alignComment(comment):
    result = []
    last = ""
    for comment in comment.split():
        # '/'을 이용한 약어를 사용하는 경우에는 반드시 공백을 하나 두도록 한다.
        if comment.find("/") != -1:
            comment = comment + " "
            
        if last == "":
            last = comment
        else:
            joinLen = len(last + comment)
            if joinLen == 8:
                join = last + comment
                last = ""
            elif joinLen < 8:
                join = last.strip() + " " + comment
                last = ""
            else:
                join = last
                last = comment
            result.append((join + " "*8)[:8])
    if last:
        result.append((last + " "*8)[:8])
    
    return "".join(result).replace("_", " ")
    
def joinComment(*args):
    def align(comment):
        comment = alignComment(comment)
        reqsp = 8 - len(comment) % 8
        if reqsp < 8:
            comment = comment + " "*reqsp
        return comment
    return "".join(map(align, args))
 
        